﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bzzb.Model;
using FreeSql.Internal.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Bzzb.Controllers
{
    public class BaoZhangSheBeiPositionController : BaseController
    {
        private readonly ILogger<BaoZhangSheBeiPositionController> _logger;
        public BaoZhangSheBeiPositionController(ILogger<BaoZhangSheBeiPositionController> logger, IFreeSql fsql) : base(fsql)
        {
            this._logger = logger;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index([FromForm] long jtid, [FromForm] int doPage = 1, [FromForm] int pageNumber = 1, [FromForm] int pageSize = 10)
        {
            long total = 0;
            List<BaoZhangSheBeiPosition> baozhangshebeipositions;
            if (doPage == 0)
            {
                baozhangshebeipositions = await _fsql.Select<BaoZhangSheBeiPosition>().Where(bzsbp => bzsbp.Jtid == jtid).ToListAsync();
            }
            else {
                baozhangshebeipositions = await _fsql.Select<BaoZhangSheBeiPosition>().Where(bzsbp => bzsbp.Jtid == jtid).Count(out total).Page(pageNumber, pageSize).ToListAsync();
                
            }
            JObject data = new();
            data.Add("total", total);
            data.Add("list", baozhangshebeipositions == null ? null : JArray.FromObject(baozhangshebeipositions));
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] BaoZhangSheBeiPosition baozhanggongjuposition)
        {
            long id = await _fsql.Insert(baozhanggongjuposition).ExecuteIdentityAsync();
            baozhanggongjuposition.Id = id;

            return RenderJson(data: baozhanggongjuposition);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long id) {
            int affrows = await _fsql.Delete<BaoZhangSheBeiPosition>().Where(bzsbp => bzsbp.Id == id).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Update([FromForm] BaoZhangSheBeiPosition baozhanggongjuposition)
        {
            int affrows = await _fsql.Update<BaoZhangSheBeiPosition>().SetSourceIgnore(baozhanggongjuposition, colval => colval == null).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Show([FromForm] long id) {
            BaoZhangSheBeiPosition baozhangshebei = await _fsql.Select<BaoZhangSheBeiPosition>().Where(bzsbp => bzsbp.Id == id).ToOneAsync();
            return RenderJson(data: baozhangshebei);
        }
    }
}
